#!/bin/bash

# AI Platform 服务管理脚本
# 使用方法: bash scripts/manage.sh [start|stop|restart|status|clean|help]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Docker 环境
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        log_error "Docker 未运行，请先启动 Docker"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null; then
        log_error "docker-compose 未安装，请先安装 docker-compose"
        exit 1
    fi
}

# 创建数据目录
create_directories() {
    log_info "创建数据目录..."
    mkdir -p "$PROJECT_ROOT/data/neo4j/data"
    mkdir -p "$PROJECT_ROOT/data/neo4j/plugins"
    mkdir -p "$PROJECT_ROOT/data/minio"
    mkdir -p "$PROJECT_ROOT/data/kafka"
    mkdir -p "$PROJECT_ROOT/data/pgvector"
}

# 启动服务
start_services() {
    log_info "启动 AI Platform 基础服务..."
    check_docker
    create_directories
    
    cd "$PROJECT_ROOT"
    log_info "启动服务..."
    docker-compose up -d
    
    log_info "等待服务启动..."
    sleep 10
    
    log_info "检查服务状态..."
    docker-compose ps
    
    echo ""
    log_success "服务启动完成！"
    echo ""
    echo "访问地址："
    echo "  Neo4j Browser:  http://localhost:7474"
    echo "  MinIO Console:   http://localhost:9001"
    echo "  Kafka:           localhost:9092"
    echo "  PostgreSQL:      localhost:5433"
    echo ""
    echo "默认认证信息："
    echo "  Neo4j:     用户名: neo4j,     密码: password123"
    echo "  MinIO:     用户名: minioadmin, 密码: minioadmin123"
    echo "  PostgreSQL: 用户名: postgres,   密码: postgres"
}

# 停止服务
stop_services() {
    log_info "停止 AI Platform 基础服务..."
    check_docker
    
    cd "$PROJECT_ROOT"
    log_info "停止服务..."
    docker-compose stop
    
    log_success "所有服务已停止！"
}

# 重启服务
restart_services() {
    log_info "重启 AI Platform 基础服务..."
    check_docker
    
    cd "$PROJECT_ROOT"
    log_info "重启服务..."
    docker-compose restart
    
    log_info "等待服务重启..."
    sleep 10
    
    log_info "检查服务状态..."
    docker-compose ps
    
    log_success "服务重启完成！"
}

# 查看服务状态
show_status() {
    log_info "AI Platform 基础服务状态"
    echo "======================================"
    check_docker
    
    cd "$PROJECT_ROOT"
    
    echo ""
    echo "容器状态："
    docker-compose ps
    
    echo ""
    echo "资源使用情况："
    if docker-compose ps -q | wc -l | grep -q "0"; then
        log_warning "没有运行中的容器"
    else
        docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}" $(docker-compose ps -q)
    fi
    
    echo ""
    echo "服务访问地址："
    echo "  Neo4j Browser:  http://localhost:7474"
    echo "  MinIO Console:   http://localhost:9001"
    echo "  Kafka:           localhost:9092"
    echo "  PostgreSQL:      localhost:5433"
    
    echo ""
    echo "服务健康检查："
    
    # 检查各个服务的连通性
    printf "  Neo4j:      "
    if curl -s http://localhost:7474 > /dev/null 2>&1; then
        echo "运行正常"
    else
        echo "无法连接"
    fi
    
    printf "  MinIO:      "
    if curl -s http://localhost:9001 > /dev/null 2>&1; then
        echo "运行正常"
    else
        echo "无法连接"
    fi
    
    printf "  Kafka:      "
    if nc -z localhost 9092 2>/dev/null; then
        echo "运行正常"
    else
        echo "无法连接"
    fi
    
    printf "  PostgreSQL: "
    if nc -z localhost 5433 2>/dev/null; then
        echo "运行正常"
    else
        echo "无法连接"
    fi
}

# 清理服务和数据
clean_services() {
    log_info "AI Platform 数据清理"
    echo "======================================"
    check_docker
    
    log_warning "警告：此操作将删除所有容器和数据，无法恢复！"
    read -p "确认继续吗？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_error "操作已取消"
        exit 1
    fi
    
    cd "$PROJECT_ROOT"
    
    # 停止并删除容器
    log_info "停止并删除容器..."
    docker-compose down
    
    # 删除容器
    log_info "删除容器..."
    docker-compose rm -f
    
    # 删除数据目录（可选）
    read -p "是否删除所有持久化数据？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "删除数据目录..."
        rm -rf "$PROJECT_ROOT/data/neo4j"
        rm -rf "$PROJECT_ROOT/data/minio"
        rm -rf "$PROJECT_ROOT/data/kafka"
        rm -rf "$PROJECT_ROOT/data/pgvector"
        log_success "数据目录已删除"
    fi
    
    # 清理无用的 Docker 资源
    log_info "清理无用的 Docker 资源..."
    docker system prune -f
    
    log_success "清理完成！"
}

# 显示帮助信息
show_help() {
    echo "AI Platform 服务管理脚本"
    echo ""
    echo "使用方法:"
    echo "  bash scripts/manage.sh [COMMAND]"
    echo ""
    echo "可用命令:"
    echo "  start     启动所有服务"
    echo "  stop      停止所有服务"
    echo "  restart   重启所有服务"
    echo "  status    查看服务状态"
    echo "  clean     清理所有数据（谨慎使用！）"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  bash scripts/manage.sh start"
    echo "  bash scripts/manage.sh status"
    echo "  bash scripts/manage.sh stop"
}

# 交互式菜单
show_menu() {
    echo "AI Platform 服务管理"
    echo "===================="
    echo "1. 启动服务"
    echo "2. 停止服务"
    echo "3. 重启服务"
    echo "4. 查看状态"
    echo "5. 清理数据"
    echo "6. 帮助"
    echo "0. 退出"
    echo ""
    read -p "请选择操作 (0-6): " choice
    
    case $choice in
        1)
            start_services
            ;;
        2)
            stop_services
            ;;
        3)
            restart_services
            ;;
        4)
            show_status
            ;;
        5)
            clean_services
            ;;
        6)
            show_help
            ;;
        0)
            echo "退出"
            exit 0
            ;;
        *)
            log_error "无效的选择"
            show_menu
            ;;
    esac
}

# 主函数
main() {
    case "${1:-menu}" in
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        status)
            show_status
            ;;
        clean)
            clean_services
            ;;
        help)
            show_help
            ;;
        menu)
            show_menu
            ;;
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 